<template>
   <!-- 权限添加用户 -->
   <div class="addMask">
      <el-dialog
         v-model="dialogVisible"
         :title="title"
         width="800"
      >
         <el-form
            :model="formData"
            ref="formRef"
            label-width="120px"
            :rules="rules"
         >
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="初始账号"
                     prop="username"
                  >
                     <el-input
                        v-model="formData.username"
                        placeholder="请输入账号"
                     ></el-input>
                  </el-form-item>

                  <el-form-item
                     label="初始密码"
                     prop="password"
                  >
                     <el-input
                        :disabled="editingUserId"
                        v-model="formData.password"
                        placeholder="请输入密码"
                     ></el-input> </el-form-item
               ></el-col>
               <el-col :span="12">
                  <el-form-item
                     label="请选择组织人员"
                     prop="member_id"
                  >
                     <el-select
                        v-model="formData.member_id"
                        :placeholder="formData.nickname ? formData.nickname : tips"
                        filterable
                        style="width: 400px"
                        clearable
                        @change="handeleSelect"
                        value-key="id"
                     >
                        <el-option
                           v-for="item in managerList"
                           :value="item.id"
                           :label="item.name"
                           :key="item.id"
                        >
                           <div style="display: flex; justify-content: space-between; align-items: center; width: 100%">
                              <span>{{ item.name }}</span>
                              <span style="color: #999; font-size: 13px">{{ item.mobile }}</span>
                           </div>
                        </el-option>
                     </el-select>
                  </el-form-item>
                  <el-form-item
                     label="姓名"
                     prop="nickname"
                  >
                     <el-input
                        v-model="formData.nickname"
                        placeholder="请输入姓名"
                        disabled
                     ></el-input> </el-form-item
               ></el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="手机号"
                     prop="mobile"
                  >
                     <el-input
                        disabled
                        v-model="formData.mobile"
                        placeholder="请输入手机号"
                        maxlength="11"
                     ></el-input>
                  </el-form-item>
                  <el-form-item
                     label="直属组织"
                     prop="org_nmae"
                  >
                     <el-input
                        v-model="organizationMember.org_nmae"
                        disabled
                        placeholder="选择组织人员后自动填充"
                     ></el-input> </el-form-item
               ></el-col>
               <el-col :span="12"
                  ><el-form-item
                     label="组织职位"
                     prop="org_id"
                  >
                     <el-input
                        v-model="organizationMember.positioon_name"
                        disabled
                        placeholder="选择组织人员后自动填充"
                     ></el-input>
                  </el-form-item>

                  <el-form-item
                     label="协助组织"
                     prop="org_ids"
                  >
                     <el-input
                        v-model="departmentList"
                        disabled
                        placeholder="选择组织人员后自动填充"
                     ></el-input> </el-form-item
               ></el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="协助职位"
                     prop="position_ids"
                  >
                     <el-input
                        v-model="assistPositionName"
                        disabled
                        placeholder="选择组织人员后自动填充"
                     ></el-input> </el-form-item
               ></el-col>
               <el-col :span="12">
                  <el-form-item
                     label="角色"
                     prop="role_id"
                  >
                     <el-select
                        placeholder="选择角色"
                        filterable
                        :clearable="true"
                        v-model="formData.role_id"
                     >
                        <el-option
                           v-for="item in tableList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"
                        />
                     </el-select> </el-form-item
               ></el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="是否超级管理员">
                     <el-radio-group v-model="formData.is_super">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
               <el-button
                  type="danger"
                  @click="closeDialog"
                  >关闭</el-button
               >
               <el-button
                  color="#6860ff"
                  @click="submitForm"
                  >确定</el-button
               >
            </span>
         </template>
      </el-dialog>
      <SelectPermission
         ref="selectPermissionRef"
         @confirm="handlePermissionConfirm"
      />
   </div>
</template>

<script setup>
   import { ref, computed, onMounted, reactive } from "vue";
   import api from "@/api/index.js";
   import { ElMessage } from "element-plus";
   const emit = defineEmits(["init"]);
   import SelectPermission from "./SelectPermission.vue";
   import { number } from "echarts";

   // 初始化
   const selectPermissionRef = ref(null);
   const formRef = ref(null);
   const dialogVisible = ref(false);
   const tableList = ref([]);
   const managerList = ref([]); //管理人员列表
   let tips = ref("请选择组织人员");
   const selectedPersonnel = ref(null); // 当前选中的人员对象
   // 表单校验规则
   const rules = {
      username: [
         { required: true, message: "请输入初始账号", trigger: "blur" },
         { min: 2, max: 20, message: "账号长度在2到20个字符之间", trigger: "blur" },
      ],
      password: [
         { required: true, message: "请输入初始密码", trigger: "blur" },
         { min: 6, max: 20, message: "密码长度在6到20个字符之间", trigger: "blur" },
      ],
      member_id: [{ required: true, message: "请选择组织人员", trigger: "change" }],
      role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
   };
   // 请求数据
   const formData = ref({
      username: "", // 用户登录名
      password: "", // 用户密码
      nickname: "", // 用户昵称
      mobile: "", // 用户手机
      member_id: "", // 组织成员ID
      role_id: "", // 主角色ID，从角色列表中选取
      role_ids: "", // 角色ID组json数组格式，如：[1,2,3,4] 从角色列表选取
      is_super: "", // 是否超级管理员
      //----------
   });
   // 组织成员
   const organizationMember = ref({
      name: "", // 姓名
      org_nmae: "", // 直属组织
      positioon_name: "", // 职位
      org_ids: "", // 协助组织
      position_ids: "", // 协助职位
   });
   // 协助职位信息
   const assistPositionName = ref("");
   const editingUserId = ref(null); // 编辑用户ID
   const handleDialog = async (row) => {
      dialogVisible.value = true;
      // 重置所有状态
      managerList.value = [];
      formData.value = {};
      organizationMember.value = {};
      editingUserId.value = null;

      // 获取角色列表
      await getRoleList();

      if (row) {
         editingUserId.value = row.id;
         await getUserInfo();
      } else {
         formData.value = {
            password: "123456",
         };
         await getManagerList();
      }
   };
   // 关闭弹窗
   const closeDialog = () => {
      dialogVisible.value = false;
      selectedPersonnel.value = null;
   };
   // 提交表单
   const submitForm = async () => {
      try {
         // 表单校验
         const valid = await formRef.value.validate();
         if (valid) {
            if (editingUserId.value) {
               await updateUser();
            } else {
               await addUser();
            }
         }
      } catch (fields) {
         console.log("表单校验失败:", fields);
         return false;
      }
   };
   // 新增用户
   const addUser = async () => {
      // 确保role_ids是正确的格式（数组转JSON字符串）
      formData.value.role_ids = [formData.value.role_id];
      if (Array.isArray(formData.value.role_ids)) {
         formData.value.role_ids = JSON.stringify(formData.value.role_ids);
      }
      // 调用API创建用户
      const res = await api.authority.addUser(formData.value);
      if (res.code === 200) {
         emit("init"); // 更新父组件表格数据
         dialogVisible.value = false; // 关闭弹窗
         ElMessage.success("创建成功");
      } else {
         ElMessage.error(res.msg || "创建失败");
      }
   };
   // 编辑用户
   const updateUser = async () => {
      const res = await api.authority.editUser({ ...formData.value, id: editingUserId.value });
      if (res.code === 200) {
         emit("init"); // 更新父组件表格数据
         dialogVisible.value = false; // 关闭弹窗
         ElMessage.success("编辑成功");
      } else {
         ElMessage.error(res.msg || "编辑失败");
      }
   };
   // 组织人员下拉列表
   const getManagerList = async (isEdit = false) => {
      // 根据模式选择不同的API
      const apiMethod = editingUserId.value ? api.authority.getPersonnelList : api.authority.getUserListByOrg;
      const res = await apiMethod({
         // page: "1",
         page_size: "1000", // 设置较大的分页大小以便一次性获取所有数据
      });
      if (res.code === 200) {
         managerList.value = res.data.data;
      } else {
         ElMessage.error(res.msg || "获取管理人员失败");
      }
   };
   // 监听组织人员ID
   const handeleSelect = async (id) => {
      // 重置所有相关字段
      resetFormFields();

      // 根据ID找到对应的人员信息
      const selectedPerson = managerList.value.find((item) => item.id === id);
      if (selectedPerson) {
         // 设置基本信息
         formData.value.nickname = selectedPerson.name;
         formData.value.mobile = selectedPerson.mobile;
         formData.value.org_ids = selectedPerson.org_ids;
         formData.value.position_ids = selectedPerson.position_ids;
         formData.value.org_id = selectedPerson.org_id;
         formData.value.member_id = selectedPerson.id;

         // 设置组织职位
         organizationMember.value.positioon_name = selectedPerson.org_position?.position_name || "无职位";

         // 获取并设置所有相关信息
         await Promise.all([fetchDirectOrg(selectedPerson.org_id), fetchAssistOrgs(selectedPerson.org_ids), fetchAssistPositions(selectedPerson.position_ids)]);
      }
   };

   // 重置表单相关字段
   const resetFormFields = () => {
      formData.value.nickname = "";
      formData.value.mobile = "";
      formData.value.org_ids = "";
      formData.value.position_ids = "";
      formData.value.org_id = "";
      departmentList.value = "";
      assistPositionName.value = "";
      organizationMember.value = {
         name: "",
         org_nmae: "",
         positioon_name: "",
         org_ids: "",
         position_ids: "",
      };
   };

   // 获取直属组织信息
   const fetchDirectOrg = async (orgId) => {
      if (!orgId) {
         organizationMember.value.org_nmae = "无直属组织";
         return;
      }

      try {
         const res = await api.authority.getOrgList({ id: orgId });
         if (res.code === 200) {
            organizationMember.value.org_nmae = res.data.name || "无直属组织";
         }
      } catch (error) {
         console.error("获取直属组织失败:", error);
         organizationMember.value.org_nmae = "获取失败";
      }
   };

   // 获取协助组织信息
   const fetchAssistOrgs = async (orgIds) => {
      if (!orgIds || !orgIds.length) {
         departmentList.value = "无协助部门";
         return;
      }

      try {
         const res = await api.authority.getOrgList();
         if (res.code === 200) {
            let _d = res.data.map((item) => ({
               id: item.id,
               name: item.name,
            }));

            departmentList.value =
               _d
                  .filter((item) => orgIds.includes(item.id))
                  .map((item) => item.name)
                  .join(",") || "无协助部门";
         }
      } catch (error) {
         console.error("获取部门列表失败:", error);
         departmentList.value = "获取失败";
      }
   };

   // 获取协助职位信息
   const fetchAssistPositions = async (positionIds) => {
      if (!positionIds || !positionIds.length) {
         assistPositionName.value = "无协助职位";
         return;
      }

      try {
         const res = await api.authority.getPositionList();
         if (res.code === 200) {
            assistPositionName.value =
               res.data.data
                  .filter((item) => positionIds.includes(item.id))
                  .map((item) => item.position_name)
                  .join(",") || "无协助职位";
         }
      } catch (error) {
         console.error("获取协助职位失败:", error);
         assistPositionName.value = "获取失败";
      }
   };

   // 用户详情
   const getUserInfo = async () => {
      const res = await api.authority.getUserInfo({ id: editingUserId.value });
      if (res.code === 200) {
         res.data.password = "123456";
         formData.value = { ...res.data };

         // 如果存在member_id，触发相关信息的获取
         if (formData.value.member_id) {
            // 等待人员列表加载完成
            await getManagerList();
            // 手动触发选择事件来加载相关信息
            await handeleSelect(formData.value.member_id);
         }
      }
   };
   const positionList = ref([]); // 岗位列表
   // 获取岗位列表
   const getPositionstList = async () => {
      if (!formData.value.position_ids) return;
      try {
         const res = await api.authority.getPositionList();
         if (res.code === 200) {
            assistPositionName.value =
               res.data.data
                  .filter((item) => formData.value.position_ids.includes(item.id))
                  .map((item) => item.position_name)
                  .join(",") || "无协助职位";
         }
      } catch (error) {
         console.error("获取职位列表失败:", error);
      }
   };
   const departmentList = ref(""); // 部门列表
   // 获取部门列表
   const getDepartmentList = async () => {
      if (!formData.value.org_ids) return;
      try {
         const res = await api.authority.getOrgList();
         if (res.code === 200) {
            let _d = res.data.map((item) => ({
               id: item.id,
               name: item.name,
            }));
            departmentList.value =
               _d
                  .filter((item) => formData.value.org_ids.includes(item.id))
                  .map((item) => item.name)
                  .join(",") || "无协助部门";
         }
      } catch (error) {
         console.error("获取部门列表失败:", error);
      }
   };
   // 获取角色列表
   const getRoleList = async () => {
      try {
         const res = await api.authority.getRoleList();
         if (res.code === 200) {
            // 方案1：强制转换为数组
            const data = Array.isArray(res.data) ? res.data : [];
            tableList.value = data.map((item) => ({
               id: item.id,
               name: item.name,
            }));
         } else {
            ElMessage.error(res.msg || "获取角色列表失败");
         }
      } catch (error) {
         console.error("获取角色列表失败:", error);
         ElMessage.error("获取角色列表失败");
      }
   };
   // 暴露组件方法
   defineExpose({
      handleDialog,
   });
</script>

<style lang="scss" scoped>
   .filter-selection {
      display: flex;
      flex-direction: column;
      gap: 8px;
   }

   .selected-info {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 13px;
      color: #606266;
   }

   ::v-deep .el-pagination.is-background .el-pager li.is-active {
      background-color: #000 !important;
   }
   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__inner:hover) {
      border-color: #626aef !important;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      border-color: #6860ff;
   }
   :deep(.el-button:hover) {
      background-color: #e2e4fd;
      color: #6860ff;
   }
   :deep(.el-input__wrapper:hover) {
      box-shadow: inset 0 0 0 1px #6860ff;
   }
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 10px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
</style>
